package com.smartcommunity.controller.village;

import com.google.common.base.Joiner;
import com.smartcommunity.entity.village.*;
import com.smartcommunity.lis.BimgClientPool;
import com.smartcommunity.api.user.UserApi;
import com.smartcommunity.base.common.CacheMap;
import com.smartcommunity.bean.entity.Role;
import com.smartcommunity.bean.entity.User;
import com.smartcommunity.bean.entity.Village;
import com.smartcommunity.bean.entity.VillageEntranceExit;
import com.smartcommunity.bean.enumeration.JudgeEnum;
import com.smartcommunity.bean.model.Pager;
import com.smartcommunity.bean.model.Result;
import com.smartcommunity.controller.BaseController;
import com.smartcommunity.entity.Unit.Unit;
import com.smartcommunity.entity.Unit.UnitSearch;
import com.smartcommunity.entity.village.dto.VillageForPeopleManage;
import com.smartcommunity.log.interceptor.Log;
import com.smartcommunity.utils.ArrayUtils;
import com.smartcommunity.utils.DateUtils;
import com.smartcommunity.service.village.VillageService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @ClassName: VillageController
 * @Description: 小区相关控制层
 * @author: zdy
 * @Date: 2020/1/7
 * @version V2.0
 */
@RestController
@RequestMapping(value = "/village")
@Api(value = "小区服务(行政区划、小区、楼栋、出入口管理)",tags = "小区管理")
@Slf4j
public class VillageController extends BaseController {

    @Autowired
    private VillageService villageService;

    @Autowired
    private UserApi userApi;

    @Autowired
    private BimgClientPool lis;

    /**
     * ==============行政区划==============
     */

    /**
     * @Description: 新增行政区划
     * @param: OrganizationVillage bean
     * @return: com.alibaba.fastjson.JSONObject
     * @auther: zdy
     * @date: 2020/1/6
     */
    @Log(info = "新增行政区划信息",module = "行政区划",function = "新增")
    @PostMapping(value = "/insertVillageOrg")
    @ApiOperation(value = "新增行政区划",notes = "新增行政区划")
    public Result insertVillageOrg(@RequestBody @ApiParam(name = "bean", value = "行政区划对象") OrganizationVillage bean) {
        log.info("接口：insertVillageOrg；新增行政区划");
        return villageService.insertVillageOrg(bean);
    }

    /**
     * @Description: 编辑行政区划
     * @param: OrganizationVillage bean
     * @return: com.alibaba.fastjson.JSONObject
     * @auther: zdy
     * @date: 2020/1/6
     */
    @Log(info = "编辑行政区划信息",module = "行政区划",function = "编辑")
    @PostMapping(value = "/updateVillageOrg")
    @ApiOperation(value = "编辑行政区划",notes = "编辑行政区划")
    public Result updateVillageOrg(@RequestBody @ApiParam(name = "bean", value = "行政区划对象")OrganizationVillage bean) {
        log.info("接口：updateVillageOrg；编辑行政区划");
        return villageService.updateVillageOrg(bean);
    }

    /**
     * @Description: 删除行政区划
     * @param: OrganizationVillage bean
     * @return: com.alibaba.fastjson.JSONObject
     * @auther: zdy
     * @date: 2020/1/6
     */
    @Log(info = "删除行政区划信息",module = "行政区划",function = "删除")
    @DeleteMapping(value = "/deleteVillageOrg")
    @ApiOperation(value = "删除行政区划",notes = "删除行政区划")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id" ,value = "行政区划id")
    })
    public Result deleteVillageOrg(@RequestParam(name = "id",required = true) String id) {
        log.info("接口：deleteVillageOrg；删除行政区划");
        return villageService.deleteVillageOrg(id);
    }


    /**
     * 获取行政区划分页列表
     *
     * @param orgName
     *            搜索关键字，支持根据机构名称搜索
     * @param pageNumber
     *            当前页
     * @param pageSize
     *            每一页展示的条数
     * @return
     */
    @Log(info = "查询行政区划信息",module = "行政区划",function = "查询")
    @GetMapping(value = "/pageVillageOrg")
    @ApiOperation(value = "获取行政区划分页列表",notes = "获取行政区划分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "text" ,value = "关键字",example = "关键字"),
            @ApiImplicitParam(name = "orgName" ,value = "行政区划名称",example = "武汉市"),
            @ApiImplicitParam(name = "orgCode" ,value = "行政区划编码",example = "420624"),
            @ApiImplicitParam(name = "parentId" ,value = "行政区划父ID",example = "1"),
            @ApiImplicitParam(name = "pageNumber" ,value = "当前页",example = "1"),
            @ApiImplicitParam(name = "pageSize" ,value = "每一页展示的条数",example = "10")
    })
    public Result pageVillageOrg(@RequestParam(required = false, name = "text") String text,
                                 @RequestParam(required = false, name = "orgName") String orgName,
                                 @RequestParam(required = false, name = "orgCode") String orgCode,
                                 @RequestParam(required = false, name = "parentId") String parentId,
                                 @RequestParam(required = false, name = "pageNumber") String pageNumber,
                                 @RequestParam(required = false, name = "pageSize") String pageSize) {
        log.info("接口：pageVillageOrg；获取行政区划分页列表");
        long st=System.currentTimeMillis();
        Map<String, Object> map = new HashMap<>();
        map.put("text", text);
        map.put("orgName", orgName);
        map.put("orgCode", orgCode);
        User user = getCurrentUser();
        String villageCode = getVillageCodeByUser(user);

        if(StringUtils.isNotBlank(villageCode)){
            //根据有权限的小区code 获取所有上级的行政区划id
            Set<String> orgIdSet = villageService.getOrgIdsByVillageCode(villageCode);
            String ids =  String.join(",", orgIdSet);
            if(StringUtils.isBlank(ids)){
                return Result.ok();
            }else {
                if(StringUtils.isNotBlank(parentId)){
                    //根据parentId获取所有子节点行政区划ID
                    Set<String> result = new HashSet<>();
                    String orgIds = villageService.getAllChildOrgId(parentId);
                    String[] arr= StringUtils.isBlank(orgIds)?new String[]{}: orgIds.split(",");
                    Set<String> parentIdSet = new HashSet<>(Arrays.asList(arr));
                    result.addAll(orgIdSet);
                    //取交集（有权限的行政区划ID，又是其子节点）
                    result.retainAll(parentIdSet);
                    ids =  String.join(",", result);
                }
                map.put("ids", ids);
            }
        }
        long speedTime=System.currentTimeMillis()-st;
        log.info("行政区划查询，条件耗时:"+speedTime);

        st=System.currentTimeMillis();
        Pager<OrganizationVillage>  page = villageService.pageVillageOrg(map, getPageNumber(pageNumber), getPageSize(pageSize));
        speedTime=System.currentTimeMillis()-st;
        log.info("行政区划查询，sql耗时:"+speedTime);
        return Result.ok(page);
    }

    /**
     * 获取小区上级机构及小区信息树
     *
     * @return
     */
    @GetMapping(value = "/listVillageTree")
    @ApiOperation(value = "获取行政区划树(包含小区数据)",notes = "获取行政区划树(包含小区数据)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号"),
            @ApiImplicitParam(name = "keyWord" ,value = "关键字,支持搜素小区名称、拼音、首字母"),
            @ApiImplicitParam(name = "build" ,value = "是否带有楼栋数据，默认false",dataType = "boolean",example = "false"),
            @ApiImplicitParam(name = "camera" ,value = "是否带有摄像机数据，默认false",dataType = "boolean",example = "false"),
            @ApiImplicitParam(name = "skipRole" ,value = "是否跳过权限过滤，默认false",dataType = "boolean",example = "false")
    })
    public Result listVillageTree(
            @RequestParam(required = false, name = "villageCode") String villageCode,
            @RequestParam(required = false, name = "keyWord") String keyWord,
            @RequestParam(required = false, name = "build") boolean build,
            @RequestParam(required = false, name = "camera") boolean camera,
            @RequestParam(required = false, name = "skipRole") boolean skipRole) {
        log.info("接口：listVillageTree；获取行政区划树");
        Map<String, Object> param = new HashMap<>();
        param.put("keyWord", keyWord);
        param.put("build", build);
        param.put("camera", camera);
        if(skipRole){
            villageCode = null;
        }
        param.put("villageCode",villageCode);
        long st=System.currentTimeMillis();
        List<OrganizationVillage>  list = villageService.listVillageTree(param);
        long speedTime=System.currentTimeMillis()-st;
        log.info("获取行政区划树:"+speedTime+"ms");
        return Result.ok(list);
    }


    @GetMapping(value = "/listOrgTree")
    @ApiOperation(value = "获取行政区划树",notes = "获取行政区划树")
    public List<OrganizationVillage> listOrgTree() {
        log.info("接口：listOrgTree；获取行政区划树");
        Map<String, Object> param = new HashMap<>();
        List<OrganizationVillage> list = villageService.OrganizationVillageOneID();
        List<OrganizationVillage> organizationList = new ArrayList<>();
        for (OrganizationVillage bean : list) {
            param.put("organizationVillage", bean);
            OrganizationVillage organization = villageService.getOrganization(param);
            organizationList.add(organization);
        }
        return organizationList;
    }

    /**
     * ==============小区管理==============
     */

    /**
     * 新增小区
     * @param bean
     * @return JSONObject
     *
     */
    @Log(info = "新增小区信息",module = "小区管理",function = "新增")
    @PostMapping(value = "/insertVillage")
    @ApiOperation(value = "新增小区",notes = "新增小区")
    public Result insertVillage(@RequestBody @ApiParam(name = "bean", value = "小区对象") Village bean) {
        log.info("接口：insertVillage；新增小区");
        //小区图片支持base64
        this.saveFileToLIS(bean);
        return villageService.insertVillage(bean);
    }

    /**
     * 删除小区
     *
     * @param villageCode
     * @return JSONObject
     *
     */
    @Log(info = "删除小区信息",module = "小区管理",function = "删除")
    @DeleteMapping(value = "/deleteVillage")
    @ApiOperation(value = "删除小区",notes = "删除小区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号")
    })
    public Result deleteVillage(@RequestParam(name = "villageCode") String villageCode) {
        log.info("接口：deleteVillage；删除小区");
        return villageService.deleteVillage(villageCode);
    }

    /**
     * 编辑小区
     *
     * @param bean
     * @return JSONObject
     *
     */
    @Log(info = "编辑小区信息",module = "小区管理",function = "编辑")
    @PostMapping(value = "/updateVillage")
    @ApiOperation(value = "编辑小区",notes = "编辑小区")
    public Result updateVillage(@RequestBody @ApiParam(name = "bean", value = "小区对象") Village bean) {
        log.info("接口：updateVillage；编辑小区");
        //小区图片支持base64
        this.saveFileToLIS(bean);
        return villageService.updateVillage(bean);
    }

    /**
     * 获取小区分页列表
     *
     * @param villageName
     * @param villageCode
     * @param address
     * @param pageNumber 当前页
     * @param pageSize 每一页展示的条数
     * @return
     */
    @Log(info = "查询小区分页列表",module = "小区管理",function = "查询")
    @GetMapping(value = "/pageVillages")
    @ApiOperation(value = "获取小区分页列表",notes = "获取小区分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "text" ,value = "小区关键字搜索，主要是小区名称和地址的模糊搜索"),
            @ApiImplicitParam(name = "villageName" ,value = "小区名称"),
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号"),
            @ApiImplicitParam(name = "address" ,value = "地址"),
            @ApiImplicitParam(name = "parentId" ,value = "父节点行政区划ID"),
            @ApiImplicitParam(name = "pageNumber" ,value = "当前页",example = "1"),
            @ApiImplicitParam(name = "pageSize" ,value = "每一页展示的条数",example = "10")
    })
    public Result pageVillages(@RequestParam(required = false, name = "text") String text,
                                        @RequestParam(required = false, name = "villageName") String villageName,
                                       @RequestParam(required = false, name = "villageCode") String villageCode,
                                       @RequestParam(required = false, name = "address") String address,
                                       @RequestParam(required = false, name = "parentId") String parentId,
                                       @RequestParam(required = false, name = "pageNumber") String pageNumber,
                                       @RequestParam(required = false, name = "pageSize") String pageSize) {
        log.info("接口：pageVillages；获取小区分页列表");
        Map<String, Object> map = new HashMap<>(3);
        //通过AuthorFilter设置的villageCode
        map.put("villageCode", villageCode);
        map.put("address", address);
        map.put("villageName", villageName);
        map.put("text", text);
        Pager<Village>  page = villageService.pageVillages(map, getPageNumber(pageNumber), getPageSize(pageSize));
        return Result.ok(page);
    }
    /**
     * 获取小区分页列表
     *
     * @param villageName
     * @param villageCode
     * @param address
     * @param pageNumber 当前页
     * @param pageSize 每一页展示的条数
     * @return
     */
    @Log(info = "查询小区分页列表(实口管控)",module = "小区管理",function = "查询")
    @GetMapping(value = "/pageVillagesForPeopleManage")
    @ApiOperation(value = "查询小区分页列表(实口管控)",notes = "查询小区分页列表(实口管控)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageName" ,value = "小区名称"),
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号"),
            @ApiImplicitParam(name = "address" ,value = "地址"),
            @ApiImplicitParam(name = "parentId" ,value = "父节点行政区划ID"),
            @ApiImplicitParam(name = "longTimeAppearTimeRange" ,required = true,value = "长期未出现天数配置"),
            @ApiImplicitParam(name = "pageNumber" ,value = "当前页",example = "1"),
            @ApiImplicitParam(name = "pageSize" ,value = "每一页展示的条数",example = "10")
    })
    public Pager<VillageForPeopleManage> pageVillagesForPeopleManage(@RequestParam(required = false, name = "villageName") String villageName,
                                                                     @RequestParam(required = false, name = "villageCode") String villageCode,
                                                                     @RequestParam(required = false, name = "address") String address,
                                                                     @RequestParam(required = false, name = "parentId") String parentId,
                                                                     @RequestParam(required = true, name = "longTimeAppearTimeRange") Integer longTimeAppearTimeRange,
                                                                     @RequestParam(required = false, name = "pageNumber") String pageNumber,
                                                                     @RequestParam(required = false, name = "pageSize") String pageSize) {
        log.info("接口：pageVillages；获取小区分页列表");

        Date rangeDate = DateUtils.addTime(new Date(),Calendar.DATE,-longTimeAppearTimeRange);
        Map<String, Object> map = new HashMap<>(3);
        map.put("villageName", villageName);
        map.put("longTimeAppearTimeRange", rangeDate);
        map.put("villageCode", villageCode);
        map.put("address", address);
        map.put("parentId", parentId);
        return villageService.pageVillagesForPeopleManage(map, getPageNumber(pageNumber), getPageSize(pageSize));
    }

    /**
     * 通过小区编号查询小区信息
     * @param villageCode
     * @return
     */
    @GetMapping("/listVillagesByVillageCode")
    @ApiOperation(value = "通过小区编号查询小区信息",notes = "通过小区编号查询小区信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号")
    })
    public List<Map<String, Object>> listVillagesByVillageCode(
            @RequestParam(required = false, name = "villageCode") String villageCode) {
        log.info("接口：listVillagesByVillageCode；通过小区编号查询小区信息");
        Map<String, Object> map = new HashMap<>(1);
        map.put("villageCode", villageCode);
        return villageService.listVillagesByVillageCode(map);
    }

    /**
     * @Description: 获取小区基本信息
     * @param: [villageCode]
     * @return: java.util.List<com.smartcommunity.entity.village.Village>
     * @auther: minsheng
     * @date: 2019/3/6 10:53
     */
    @GetMapping(value = "/listAllVillage")
    @ApiOperation(value = "获取小区基本信息",notes = "获取小区基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号")
    })
    public List<Village> listAllVillage(@RequestParam(required = false, name = "villageCode") String villageCode) {
        log.info("接口：listAllVillage；获取小区基本信息");
        Map<String, Object> param = new HashMap<>(1);
        param.put("villageCode", villageCode);
        List<Village> villageList = villageService.getAllVillage(param);
        return villageList;
    }

    /**
     * @Description: 保持小区图片公共方法
     * @param: [bean, imgBase64Str]
     * @return: boolean
     * @author: minsheng
     * @date: 2019/1/10 11:25
     */
    private void saveFileToLIS(Village bean){
        try {
            String imgBase64Str = bean.getImgBase64Str();
            if (StringUtils.isNotEmpty(imgBase64Str) && Base64.isBase64(imgBase64Str)) {
                byte[] bytes = Base64.decodeBase64(imgBase64Str);
                String imgUrl = lis.uploadImageForever(bytes);
                bean.setPicUrl(imgUrl);
            }
        } catch (Exception e) {
            log.error("VillageController:saveFileToLIS error,",e);
        }
    }


    /**
     * @Description: 根据小区编号查询单个小区
     * @param: [villageCode]
     * @return: com.smartcommunity.entity.village.Village
     * @auther: minsheng
     * @date: 2019/3/18 10:41
     */
    @Log(info = "查询单个小区详细信息",module = "小区管理",function = "查询")
    @GetMapping(value = "/getVillage")
    @ResponseBody
    @ApiOperation(value = "根据小区编号查询单个小区",notes = "根据小区编号查询单个小区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号")
    })
    public Village getVillage(@RequestParam(name = "villageCode") String villageCode) {
        log.info("接口：getVillage；根据小区编号查询单个小区");
        return villageService.getVillage(villageCode);
    }


    /**
     * ===============房屋管理=============
     *
     */

    /**
     * 通过小区编号和楼栋编号获取房屋信息
     * @return
     */
    @PostMapping(value = "/listHousesByBuilding")
    @ApiOperation(value = "通过小区编号和楼栋编号获取房屋信息",notes = "通过小区编号和楼栋编号获取房屋信息")
    public List<Map<String, Object>> listHousesByBuilding(@RequestBody @ApiParam(name = "house", value = "房屋对象") House house) {
        log.info("接口：listHousesByBuilding；通过小区编号和楼栋编号获取房屋信息");
        return villageService.listHousesByBuilding(house);
    }

    /**
     * 获取房屋列表
     * @param house
     * @return
     */
    @Log(info = "查询房屋列表",module = "小区管理",function = "查询")
    @PostMapping(value = "/pageHouses")
    @ApiOperation(value = "获取房屋列表",notes = "获取房屋列表")
    public Pager<House> pageHouses(@RequestBody @ApiParam(name = "house", value = "房屋对象") House house) {
        log.info("接口：pageHouses；获取房屋列表");
        return villageService.pageHousesByBuilding(house);
    }


    /**
     * 通过住户身份证查询住房信息,
     *
     * @param villageCode
     *            小区编码
     * @param credentialType
     *            证件类型
     * @param credentialNo
     *            证件号
     * @return
     */
    @GetMapping(value = "/listHouses")
    @ApiOperation(value = "通过住户身份证查询住房信息",notes = "通过住户身份证查询住房信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号"),
            @ApiImplicitParam(name = "credentialType" ,value = "证件类型"),
            @ApiImplicitParam(name = "credentialNo" ,value = "证件编号")
    })
    public List<Map<String, Object>> listHouses(@RequestParam(required = false, name = "villageCode") String villageCode,
                                                @RequestParam(required = false, name = "credentialType") String credentialType,
                                                @RequestParam(required = false, name = "credentialNo") String credentialNo) {
        log.info("接口：listHouses；通过住户身份证查询住房信息");
        Map<String, String> map = new HashMap<>(3);
        map.put("villageCode", villageCode);
        map.put("credentialNo", credentialNo);
        map.put("credentialType", credentialType);
        return villageService.listHouses(map);
    }


    /**
     * ================楼栋管理==============
     */

    /**
     * @Description: 新增楼栋
     * @param: [build]
     * @return: void
     * @author: zdy
     * @date: 2020/1/9
     */
    @Log(info = "新增楼栋信息",module = "楼栋管理",function = "新增")
    @PostMapping("/insertBuilding")
    @ResponseBody
    @ApiOperation(value = "新增楼栋信息",notes = "新增楼栋信息")
    public Result insertBuilding(@RequestBody @ApiParam(name = "build", value = "楼栋对象") Building build)  {
        log.info("接口：addBuild；新增楼栋");
        return villageService.addBuilding(build);
    }
    /**
     * @Description: 更新楼栋
     * @param: [build]
     * @return: void
     * @author: zdy
     * @date: 2020/1/9
     */
    @Log(info = "更新楼栋信息",module = "楼栋管理",function = "更新")
    @PostMapping("/updateBuild")
    @ResponseBody
    @ApiOperation(value = "更新楼栋信息",notes = "更新楼栋信息")
    public Result updateBuild(@RequestBody @ApiParam(name = "build", value = "楼栋对象") Building build) {
        log.info("接口：updateBuild；更新楼栋信息");
        return villageService.updateBuild(build);
    }
    /**
     * @Description: 删除楼栋信息
     * @param: [id]
     * @return: void
     * @author: zdy
     * @date: 2020/1/9
     */
    @Log(info = "删除楼栋信息",module = "楼栋管理",function = "删除")
    @DeleteMapping("/deleteBuild")
    @ResponseBody
    @ApiOperation(value = "删除楼栋",notes = "删除楼栋")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id" ,value = "楼栋id，多个以逗号分隔")
    })
    public Result deleteBuild(@RequestParam(name = "id",required = true) String id) {
        log.info("接口：deleteBuild；删除楼栋信息");
        return villageService.deleteBuild(id);
    }

    /**
     * 获取楼栋列表
     * @return
     */
    @Log(info = "查询楼栋列表",module = "楼栋管理",function = "查询")
    @PostMapping(value = "/pageBuildings")
    @ApiOperation(value = "获取楼栋列表",notes = "获取楼栋列表")
    public Pager<Building> pageBuildings(@RequestBody @ApiParam(name = "build", value = "楼栋对象") Building build) {
        log.info("接口：pageBuildings；获取楼栋列表，返回Pager<Building>");
        return villageService.pageBuildings(build);
    }



    /**
     * 查询楼栋编号
     *
     * @param villageCode
     *            小区编号
     * @param buildingNo
     *            楼栋编号
     * @return
     */
    @Log(info = "查询楼栋编号信息",module = "楼栋管理",function = "查询")
    @GetMapping(value = "/pageBuildingNos")
    @ApiOperation(value = "查询楼栋编号",notes = "查询楼栋编号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号"),
            @ApiImplicitParam(name = "buildingNo" ,value = "楼栋编号"),
            @ApiImplicitParam(name = "address" ,value = "地址"),
            @ApiImplicitParam(name = "houseNo" ,value = "房屋编号"),
            @ApiImplicitParam(name = "pageNumber" ,value = "当前页",example = "1"),
            @ApiImplicitParam(name = "pageSize" ,value = "每一页展示的条数",example = "10")
    })
    public Pager<House> pageBuildingNos(@RequestParam(required = false, name = "villageCode") String villageCode,
                                        @RequestParam(required = false,name = "buildingNo") String buildingNo,
                                        @RequestParam(required = false,name = "address") String address,
                                        @RequestParam(required = false,name = "houseNo") String houseNo,
                                        @RequestParam(required = false, name = "pageNumber") int pageNumber,
                                        @RequestParam(required = false, name = "pageSize") int pageSize) {
        log.info("接口：pageBuildingNos；查询楼栋编号");
        Map<String, String> map = new HashMap<>(4);
        map.put("villageCode", villageCode);
        map.put("houseNo", houseNo);
        map.put("buildingNo", buildingNo);
        map.put("address", address);
        return villageService.pageBuildingNos(map, pageNumber, pageSize);
    }

    /**
     * 查询楼栋单元列表
     * @return
     */
    @Log(info = "查询楼栋单元列表",module = "楼栋管理",function = "查询")
    @PostMapping(value = "/pageUnits")
    @ApiOperation(value = "查询楼栋单元列表",notes = "查询楼栋单元列表")
    public Pager<Unit> pageUnitNos(@RequestBody @ApiParam(name = "model", value = "单元查询条件") UnitSearch model) {
        log.info("接口：pageBuildings；查询楼栋单元列表，返回Pager<Unit>");
        return villageService.pageUnits(model);
    }

    /**
     * ==========小区出入口===========
     */
    /**
     * @Title: addVillageEntranceExit
     * @Description: 新增小区出入口
     * @param @param villageEntranceExit
     * @return Result
     * @author zdy
     */
    @Log(info = "新增小区出入口",module = "小区管理",function = "新增")
    @PostMapping("/insertVillageEntranceExit")
    @ApiOperation(value = "新增小区出入口",notes = "新增小区出入口")
    public Result insertVillageEntranceExit(@RequestBody @ApiParam(name = "villageEntranceExit", value = "小区出入口对象") VillageEntranceExit villageEntranceExit) {
        log.info("接口：insertVillageEntranceExit；新增小区出入口");
        return 	villageService.insertVillageEntranceExit(villageEntranceExit);
    }

    /**
     * @Title: updateVillageEntranceExit
     * @Description: 编辑小区出入口
     * @param @param villageEntranceExit
     * @return Result
     * @author zdy
     */
    @Log(info = "编辑小区出入口",module = "小区管理",function = "编辑")
    @PostMapping("/updateVillageEntranceExit")
    @ApiOperation(value = "编辑小区出入口",notes = "编辑小区出入口")
    public Result updateVillageEntranceExit(@RequestBody @ApiParam(name = "villageEntranceExit", value = "小区出入口对象") VillageEntranceExit villageEntranceExit) {
        log.info("接口：updateVillageEntranceExit；编辑小区出入口");
        return 	villageService.updateVillageEntranceExit(villageEntranceExit);
    }

    /**
     * 删除小区出入口
     * @param id（必填），数据库记录标识，支持批量删除，多个id用“,”号分割，例如：1,2,3
     */
    @Log(info = "删除小区出入口",module = "小区管理",function = "删除")
    @DeleteMapping(value = "/deleteVillageEntranceExit")
    @ApiOperation(value = "删除小区出入口",notes = "删除小区出入口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id" ,value = "小区出入口id")
    })
    public Result deleteVillageEntranceExit(@RequestParam(name = "id") String id){
        log.info("接口：deleteVillageEntranceExit；删除小区");
        return villageService.deleteVillageEntranceExit(id);
    }

    /**
     * 获取小区出入口分页列表
     *
     * @param name 出入口名称
     * @param pageNumber 当前页
     * @param pageSize 每一页展示的条数
     * @return
     */
    @GetMapping(value = "/pageVillageEntranceExits")
    @ApiOperation(value = "获取小区出入口分页列表",notes = "获取小区出入口分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name" ,value = "小区出入口名称"),
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号"),
            @ApiImplicitParam(name = "villageName" ,value = "小区名称"),
            @ApiImplicitParam(name = "pageNumber" ,value = "当前页",example = "1"),
            @ApiImplicitParam(name = "pageSize" ,value = "每一页展示的条数",example = "10")
    })
    public Pager<VillageEntranceExit> pageVillageEntranceExits(@RequestParam(required = false, name = "name") String name,
                                                               @RequestParam(required = false, name = "villageCode") String villageCode,
                                                               @RequestParam(required = false, name = "villageName") String villageName,
                                                               @RequestParam(required = false, name = "pageNumber") String pageNumber,
                                                               @RequestParam(required = false, name = "pageSize") String pageSize) {
        log.info("接口：getVillageEntranceExitList；获取小区出入口分页列表");
        Map<String, Object> map = new HashMap<>(3);
        map.put("villageName", villageName);
        map.put("villageCode", villageCode);
        map.put("name", name);
        return villageService.pageVillageEntranceExits(map, getPageNumber(pageNumber), getPageSize(pageSize));
    }

    /**
     * 通过小区编号查询小区出入口信息
     *
     * @param villageCode
     * @return
     */
    @GetMapping("/listVillageEntranceExits")
    @ApiOperation(value = "通过小区编号查询小区出入口信息",notes = "通过小区编号查询小区出入口信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号")
    })
    public Result listVillageEntranceExits(
            @RequestParam(required = false, name = "villageCode") String villageCode) {
        log.info("接口：getVillageEntranceExit；通过小区编号查询小区出入口信息");
        Map<String, String> map = new HashMap<>(10);
        if (org.apache.commons.lang.StringUtils.trimToNull(villageCode) == null) {
            User user = getCurrentUser();
            if(user != null&&!user.isAdmin()) {
                Result<List<String>> result = userApi.getCurrentUserVillage(JudgeEnum.yes.getCode());
                if(!result.isOk()){
                    return result;
                }
                villageCode = Joiner.on(",").join(result.getData());

            }
        }
        map.put("villageCode", villageCode);
        return Result.ok(villageService.listVillageEntranceExits(map));
    }



    /**
     * @Description: 根据小区父ID获取小区列表
     * @param: [parentId, villageName, villageCode]
     * @return: java.util.List<com.smartcommunity.entity.village.Village>
     * @author: minsheng
     * @date: 2019/1/14 16:42
     */
    @PostMapping(value = "/pageVillageByParentId")
    @ApiOperation(value = "根据小区父ID获取小区列表",notes = "根据小区父ID获取小区列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId" ,value = "父级id"),
            @ApiImplicitParam(name = "villageName" ,value = "小区名称"),
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号")
    })
    public Pager<Village> pageVillageByParentId(@RequestParam(name = "parentId")String parentId,
                                                @RequestParam(required = false,name = "villageName")String villageName,
                                                @RequestParam(required = false,name = "villageCode")String villageCode,
                                                @RequestParam(required = false, name = "pageNumber") int pageNumber,
                                                @RequestParam(required = false, name = "pageSize") int pageSize) {
        log.info("接口：pageVillageByParentId；根据小区父ID获取小区列表");
        Map<String, String> map = new HashMap<>(3);
        map.put("villageCode", villageCode);
        map.put("parentId", parentId);
        map.put("villageName", villageName);
        return villageService.pageVillageByParentId(map,pageNumber,pageSize);
    }
    /**
     * @Description: 根据orgId查询小区信息
     * @param: [recordMap]
     * @return: java.util.List<com.smartcommunity.entity.village.Village>
     * @author: minsheng
     * @date: 2019/1/16 18:36
     */
    @PostMapping("/listVillagesByOrgId")
    @ApiOperation(value = "根据orgId查询小区信息",notes = "根据orgId查询小区信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "recordMap" ,value = "recordMap")
    })
    public List<Village> listVillagesByOrgId(@RequestParam Map<String, Object> recordMap) {
        log.info("接口：listVillagesByOrgId；根据orgId查询小区信息");
        return villageService.listVillagesByOrgId(recordMap);
    }


    /**
     * 查询房屋编号
     *
     * @param villageCode
     *            小区编号
     * @param buildingNo
     *            楼栋编号
     * @return
     */
    @GetMapping(value = "/pageHouseNos")
    @ApiOperation(value = "查询房屋编号",notes = "查询房屋编号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode" ,value = "小区编号"),
            @ApiImplicitParam(name = "buildingNo" ,value = "楼栋编号"),
            @ApiImplicitParam(name = "address" ,value = "地址"),
            @ApiImplicitParam(name = "unitNo" ,value = "单元号"),
            @ApiImplicitParam(name = "houseNo" ,value = "房屋编号")
    })
    public Pager<House> pageHouseNos(@RequestParam(required = false, name = "villageCode") String villageCode,
                                     @RequestParam(required = false,name = "buildingNo") String buildingNo,
                                     @RequestParam(required = false,name = "address") String address,
                                     @RequestParam(required = false,name = "unitNo") String unitNo,
                                     @RequestParam(required = false,name = "houseNo") String houseNo,
                                     @RequestParam(required = false, name = "pageNumber") int pageNumber,
                                     @RequestParam(required = false, name = "pageSize") int pageSize) {
        log.info("接口：pageHouseNos；查询房屋编号");
        Map<String, String> map = new HashMap<>(5);
        map.put("villageCode", villageCode);
        map.put("unitNo", unitNo);
        map.put("houseNo", houseNo);
        map.put("buildingNo", buildingNo);
        map.put("address", address);
        return villageService.pageHouseNos(map, pageNumber, pageSize);
    }
    
    @PostMapping(value = "/queryAllVillage")
    @ApiOperation(value = "查询所有小区",notes = "查询所有小区")
    public List<SysVillage> queryAllVillage(){
        return villageService.queryAllVillage();
    }

    @GetMapping(value = "/queryVillagePeopleManageInfo")
    @ApiOperation(value = "根据小区编号查询小区实口管控信息", notes = "根据小区编号查询小区实口管控信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "villageCode", value = "小区编号")
    })
    public int queryVillagePeopleManageInfo (@RequestParam(required = false, name = "villageCode") String villageCode) {
        log.info("接口：queryVillagePeopleManageInfo；根据小区编号查询小区实口管控信息");
        return villageService.queryVillagePeopleManageInfo(villageCode);
    }

    //获取用户关联角色权限的小区ID及行政区划ID
    private String getVillageCodeByUser(User user){
        String villageCode = "";
        List<String> villageCodeList = new ArrayList<>();
        for (Role role: user.getRoleList()) {
            villageCode = CacheMap.REL_ROLE_VILLAGE.get(role.getId());
            if(StringUtils.isEmpty(villageCode)){
                continue;
            }
            villageCodeList.addAll(Arrays.asList(villageCode.split(",")));
        }
        villageCode = ArrayUtils.toString(villageCodeList);
        return villageCode;
    }

    /**
     * 获取小区上级机构及小区信息树
     *
     * @return
     */
    @PostMapping(value = "/villageTree")
    @ApiOperation(value = "获取行政区划树(包含小区数据)",notes = "获取行政区划树(包含小区数据)")
    public Result villageTree(@RequestBody TreeSearchModel model) {
        log.info("接口：listVillageTree；获取行政区划树");
        long st=System.currentTimeMillis();
        List<Tree>  list = villageService.villageTree(model);
        long speedTime=System.currentTimeMillis()-st;
        log.info("获取行政区划树:"+speedTime+"ms");
        return Result.ok(list);
    }

}
